﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
using System.Web.Security;

namespace Cn.Cellula.App.Lib.MiniTop {
    public class AppKey {
        public const String FormTitle = "from_title";
        public const String MasterAddress = "master_address";
        public const String HostAddress = "host_address";
        public const String LoginPage = "login_page";
        public const String LogoutPage = "logout_page";
        public const String AutoFixFormSize = "auto_fix_form_size";
        public const String MainFormWidth = "main_form_width";
        public const String MainFormHeight = "main_from_height";
        public const String OneInstance = "one_instance";
        public const String AutoRun = "auto_run";
        public const String AutoHide = "auto_hide_onfirstrun";
        public const String EnableScroll = "enable_scroll";
        public const String HelpPage = "help_page";
        public const String EmailSmtpServer = "email_smtp_server";
        public const String EmailPop3Server = "email_pop3_server";
        public const String EmailUserName = "email_username";
        public const String EmailPwd = "email_pwd";
        public const String EmailClientTool = "email_client_tool";
        public const String EmailAutoAlert = "email_auto_alert";
        public const String EmailAlertTimer = "email_alert_timer";
        public const String EmailAlertRing = "email_alert_ring";
        public const String AlertTimerEanbled = "alert_time_enabled";
        public const String AlertTimerMinutes = "alert_time_minutes";
        public const String AlertInvokeJs = "alert_invoke_js";
        public const String AlertInvokeJsArgs = "alert_invoke_js_args";
        public const String OnTop = "on_top";

    }
    public class MySetting {
        private static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public const String MASTER_ADDRESS = "http://oa.enraynet.com:9101/";
        public const String HOST_ADDRESS = "http://210.83.203.121:9102/";
        public const String LOGIN_PAGE = "Port/MiniTopLogin.aspx";
        public const String LOGOUT_PAGE = "Port/MiniTopLogin.aspx";
        public const String FORM_TITLE = "Cellula MiniTop";
        public const String SETTING_PATH = @"C:\minitop";
        private XmlDocument _Doc;
        private String _Path = SETTING_PATH;
        private String _FilePath;
        public static MySetting Instance = null;
        private  MySetting() {
            _FilePath = _Path+@"\Settings.xml";
            if (!Directory.Exists(_Path)) {
                Directory.CreateDirectory(_Path);
            }
            if (!File.Exists(_FilePath)) {
                StreamWriter sr = File.CreateText(_FilePath);
                sr.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?><root><app_settings></app_settings></root>");
                sr.Close();
                sr.Dispose();
                log.Debug("Settings.xml not exists,Created!");
            }
            if (_Doc == null) {
                _Doc = new XmlDocument();
            }
            try {
                _Doc.Load(_FilePath);
            } catch (Exception ex) {
                log.Error("Load xml file exception:" + ex.Message);
            }
        }
        public static MySetting CreateInstance() {
            if (Instance == null) Instance = new MySetting();
            return Instance;
        }

        public void SetAndSave(String rKey, String rVal) {
            Set(rKey, rVal);
            _Doc.Save(_FilePath);
        }
        public void Set(String rKey, String rVal) {
            XmlNode asNode = _Doc.SelectSingleNode("//app_settings");
            try {
                XmlNode node = _Doc.SelectSingleNode("//app[@key='" + rKey + "']");
                if (node == null) {
                    node = _Doc.CreateElement("app");
                    XmlAttribute key = _Doc.CreateAttribute("key");
                    key.Value = rKey;
                    node.Attributes.Append(key);
                    XmlAttribute val = _Doc.CreateAttribute("value");
                    node.Attributes.Append(val);
                    asNode.AppendChild(node);
                }
                node.Attributes["value"].Value = rVal;
            } catch(Exception ex) {
                log.Error("Set:" + ex.Message);
            }
        }

        public void Set(IList<KeyValuePair<String, String>> rList) {
            foreach (KeyValuePair<String, String> kv in rList) {
                Set(kv.Key, kv.Value);
            }
            _Doc.Save(_FilePath);
        }
        public String Get(String rKey) {
            String val = "";
            try {
                XmlNode node = _Doc.SelectSingleNode("//app[@key='" + rKey + "']");
                if (node == null)
                    return "";
                else
                    return node.Attributes["value"].Value;
            } catch (Exception ex) {
                log.Error("Get:"+ex.Message);
            }
            return val;
        }
        public String GetLoginUrl() {
            try {
                //return Get(AppKey.HostAddress) + Get(AppKey.LoginPage);
                return MySetting.HOST_ADDRESS + MySetting.LOGIN_PAGE;
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "about:blank";
            }
        }
        public String GetLogoutUrl() {
            try {
                //String url = Get(AppKey.HostAddress) + Get(AppKey.LogoutPage);
                String url = MySetting.HOST_ADDRESS + MySetting.LOGIN_PAGE;
                if (String.IsNullOrEmpty(url)) {
                    return GetLoginUrl();
                } else {
                    return url;
                }
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "about:blank";
            }
        }
        public Boolean RegistRunOnWindowsStart(String rFilePath) {
            RegistryKey hklm = Registry.LocalMachine;//需要引用 Microsoft.Win32   
            RegistryKey run = hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            string name = rFilePath.Substring(rFilePath.LastIndexOf(@"\") + 1);
            try {
                run.SetValue(name, rFilePath);
                hklm.Close();
            } catch (Exception ex){
                log.Error(ex.Message);
                return false;
            } finally {
                hklm.Close();
            }
            return true;
        }
        public Boolean UnRegistRunOnWindowsStart(String rFilePath) {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey run = hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            string name = rFilePath.Substring(rFilePath.LastIndexOf(@"\") + 1);
            try {
                run.DeleteValue(name);
                hklm.Close();
            } catch (Exception ex) {
                log.Error(ex.Message);
                return false;
            } finally {
                hklm.Close();
            }
            return true;
        }
        public static String PwdMark(String rPwd) {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(rPwd+"QWw&2s", "md5");
        }
    }
}
